import api from '@/api'
import * as types from '../mutation-types'
import _ from 'lodash'

// initial state
const state = {
  all: [],
  fetched: false // 列表是否已获取
}

// getters
const getters = {
  all: state => state.all,
  warranty: (state) => {
    return _.find(state.all, (item) => {
      return item.type === 10 && item.plugin === 'warranty'
    }) || {}
  }
}

// actions
const actions = {
  async fetchAllApps ({ commit, state }, { force } = {}) {
    if (force || !state.fetched) {
      let apps = await api.plugin.list()
      commit(types.ADD_APPS, apps.data.list)
      commit(types.APPS_FETCHED, true)
      return apps
    }
  }
}

// mutations
const mutations = {
  [types.ADD_APPS] (state, apps) {
    state.all = apps
  },
  [types.APPS_FETCHED] (state, fetched) {
    state.fetched = fetched
  }
}

export default {
  namespaced: true,
  state,
  getters,
  actions,
  mutations
}
